package org.hackystat.ui.projectviewer.gwt.client.panels;

import org.hackystat.ui.projectviewer.gwt.client.CSSStyles;
import org.hackystat.ui.projectviewer.gwt.client.common.MainPanelWidget;
import org.hackystat.ui.projectviewer.gwt.client.common.types.ProjectData;
import org.hackystat.ui.projectviewer.gwt.client.dataprovider.DataProviderMediator;
import org.hackystat.ui.projectviewer.gwt.client.widgets.PanelTitleWidget;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ClickListenerCollection;
import com.google.gwt.user.client.ui.SourcesClickEvents;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Displays project summary and allows sensor data download.
 *
 * @author Pavel Senin.
 *
 */
public class DailyDairyPanel extends MainPanelWidget implements ClickListener, SourcesClickEvents {

  private final ClickListenerCollection clickListeners = new ClickListenerCollection();

  /* the outer and inner frames */
  private final VerticalPanel outer = new VerticalPanel();
  private final VerticalPanel inner = new VerticalPanel();

  /* the project name Title */
  private final PanelTitleWidget projectTitle = new PanelTitleWidget();

  private String currPrjName;
  private ProjectData currPrjData;

  // needed for time measurements
  private long startTimeMillis;

  // private static final String DEL = "|";

  /**
   * Creates an instance and reports a handler.
   *
   * @return The prjectData panel instance.
   */
  public static MPHandler init() {
    return new MPHandler("dailyDairy") {
      public MainPanelWidget createInstance() {
        return new DailyDairyPanel();
      }
    };
  }

  /**
   * Instantiates the panel.
   *
   */
  public DailyDairyPanel() {

    // making up panels and wait images
    outer.setStyleName(CSSStyles.INFO_PANEL_STYLE);
    outer.setVerticalAlignment(VerticalPanel.ALIGN_TOP);
    outer.add(inner);
    inner.setWidth("100%");

    // laying down all panels and tables

    inner.add(projectTitle);

    initWidget(outer);
  }

  /**
   * Set the info for the project specified.
   *
   * @param projectId The project name.
   */
  public void setProject(final String projectId) {
    if (DataProviderMediator.getInstance().lock()) {
      // do a little panel cleanup first
      projectTitle.setWait(true);
      projectTitle.setSingleTitle("getting data ...");
      // Setup the callback from the service.
      AsyncCallback<ProjectData> callback = new AsyncCallback<ProjectData>() {
        // If the call was successful, we will get back the result of authorization.
        public void onSuccess(ProjectData s) {
          DataProviderMediator.getInstance().unlock();
          if (Log.isDebugEnabled()) {
            long endTimeMillis = System.currentTimeMillis();
            float durationSeconds = (endTimeMillis - startTimeMillis) / 1000F;
            Log.debug("PDP-Pane: unlocked. success in : " + durationSeconds + " seconds");
          }
          currPrjData = s;
          currPrjName = s.getName();
          projectTitle.setWait(false);
          projectTitle.setSingleTitle(s.getName());
        }

        // Something went wrong with the call. Handle the issue how you'd like.
        public void onFailure(Throwable ex) {
          DataProviderMediator.getInstance().unlock();
          if (Log.isDebugEnabled()) {
            long endTimeMillis = System.currentTimeMillis();
            float durationSeconds = (endTimeMillis - startTimeMillis) / 1000F;
            Log.debug("PDP-Pane: unlocked. failure in : " + durationSeconds + " seconds");
          }
          Window.alert("Unknown exception happend during RPC call. \n Please provide feedback "
              + "to hackystat-dev@googlegroups.com. \n Error: " + ex.getMessage());
        }
      };
      if (Log.isDebugEnabled()) {
        startTimeMillis = System.currentTimeMillis();
        Log.debug("PDP-Pane: RPC locked. getting project info for " + projectId);
      }
      DataProviderMediator.getInstance().getProjectData(projectId, callback);
    }
    else {
      Window.alert("RPC is locked, unable to proceed with communications. \n Please provide "
          + "feedback to hackystat-dev@googlegroups.com.");
    }
  }

  /**
   * {@inheritDoc}
   */
  public void addClickListener(ClickListener listener) {
    this.clickListeners.add(listener);
  }

  /**
   * {@inheritDoc}
   */
  public void removeClickListener(ClickListener listener) {
    this.clickListeners.remove(listener);
  }

  /**
   * Reports current project selection.
   *
   * @return The current project selection.
   */
  public String getProjectSelection() {
    return this.currPrjName;
  }

  /**
   * Reports current project data.
   *
   * @return The current project data.
   */
  public ProjectData getProjectData() {
    return this.currPrjData;
  }

  /**
   * {@inheritDoc}
   */
  public void onClick(Widget sender) {
    assert true;
  }

}
